package cn.com.kh;

import cn.com.service.GeneralService;
import net.sf.json.JSONObject;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.StringWriter;
import java.util.Properties;

/**
 * @projectName: ngsapitask-ms
 * @package: cn.com.kh
 * @className: MSUtil
 * @author: LiJT
 * @description: TODO
 * @date: 2024-01-15 18:29
 * @version: 1.0
 */
public class MSUtil {

    /*
     * @param contentJson:入参Json
     * @param resourcePath:模板路径
     * @param filename:文件名
     * @param charset:字符集
     * @return String
     * @author LiJT
     * @description TODO
     * @date 2024-01-15 18:34
     */
    public static String getMergeContent(String contentJson, String resourcePath, String filename, String charset) throws Exception {
        VelocityEngine ve = new VelocityEngine();
        Properties p = new Properties();

        if (isEmpty(resourcePath)) {
            p.setProperty("file.resource.loader.path", GeneralService.groovyPath);
        } else {
            p.setProperty("file.resource.loader.path", resourcePath);
        }
        ve.init(p);
        new JSONObject();
        JSONObject jsonObj = JSONObject.fromObject(contentJson);
        VelocityContext context = new VelocityContext();
        context.put("dynamicPage", jsonObj);
        StringWriter writer = new StringWriter();
        Template t = ve.getTemplate(filename, charset);
        t.merge(context, writer);
        String content = writer.toString();
        return content;
    }

    public static boolean isEmpty(String str) {
        return (str == null) || (str.length() == 0);
    }

}
